import java.sql.*;

public class DBAccess {
    private Connection conn = null;
    private Statement stmt = null;
    public ResultSet rs = null;
    private PreparedStatement prestmt = null;

    //Access数据库连接驱动程序
    private String driver = "sun.jdbc.odbc.JdbcOdbcDriver";

    //数据库连接方式1
    //private String url="jdbc:odbc:MS Access Database; DBQ=D:\\java\\book.mdb";
    //数据库连接方式2
    private String url = "jdbc:odbc:book2";//自定义数据源名
    private String user = "";
    private String pwd = "";
    public String notes = "数据库操作提示";


    //实例方法1：实现数据库连接
    public void dbconn() {
        try {
            Class.forName(driver);//加载驱动程序
            conn = DriverManager.getConnection(url, user, pwd);//建立连接
            stmt = conn.createStatement();//向数据库发送对象
            //捕获类对象异常
        } catch (ClassNotFoundException ec) {
            ec.printStackTrace();
            //数据库异常
        } catch (SQLException es) {
            es.printStackTrace();
            //其他异常
        } catch (Exception ex) {
            ex.printStackTrace();
        }
		/*try
		{
			con=DriverManager.getConnection("jdbc:odbc:DBConn","","");
			sql=con.createStatement();
			rs=sql.executeQuery("SELECT * FROM DBConn");
			while(rs.next())
			{
			}
		}*/
    }

    //实例方法2：查询数据库记录，并返回查询结果
    public ResultSet dbSelect(String selString) {
        try {
            rs = stmt.executeQuery(selString);//执行select语句
        } catch (SQLException es) {
            es.printStackTrace();
        }
        return rs;
    }

    //实例方法3：更新数据库记录，并返回操作结果提示信息
    public String dbUpdate(String updateString) {
        try {
            prestmt = conn.prepareStatement(updateString);//生成预编译
            prestmt.executeUpdate();//执行update语句
            notes = "更新成功";
        } catch (SQLException es) {
            es.printStackTrace();
            notes = "数据库更新出现异常";
        }
        return notes;
    }

    //实例方法4：插入数据记录，并返回操作结果提示信息
    public String dbInsert(String insertString) {
        try {
            System.out.println(insertString);
            prestmt = conn.prepareStatement(insertString);
            prestmt.executeUpdate();
            notes = "记录插入成功";
        } catch (SQLException es) {
            es.printStackTrace();
            notes = "数据库记录插入异常";
        }
        return notes;
    }

    //实例方法5：删除数据库记录
    public String dbDelete(String delString) {
        try {
            prestmt = conn.prepareStatement(delString);
            prestmt.executeUpdate();
            notes = "记录删除成功";
        } catch (SQLException es) {
            es.printStackTrace();
            notes = "数据库删除异常";
        }
        return notes;
    }

    //实例方法6：关闭数据库连接
    public void dbclose() {
        if (conn != null) {
            try {
                rs.close();//关闭记录集
                stmt.close();//关闭SQL语句发送
                conn.close();//关闭数据库连接
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

